﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
using ArrayList=System.Collections.ArrayList;

namespace Library
{
    class EnumHelper
    {
        public static string GetDescription(Enum value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            string description = value.ToString();
            FieldInfo fieldInfo = value.GetType().GetField(description);
            EnumDescriptionAttribute[] attributes =
                (EnumDescriptionAttribute[])
                fieldInfo.GetCustomAttributes(typeof(EnumDescriptionAttribute), false);

            if (attributes != null && attributes.Length > 0)
            {
                description = attributes[0].Description;
            }
            return description;
        }

        /// <summary>
        /// Converts the Enum type to an IList{T} compatible object.
        /// </summary>
        /// <param name="type">The <see cref="Enum"/> type.</param>
        /// <returns>An <see cref="IList{T}"/> containing the enumerated
        /// type value and description.</returns>
        public static IList ToList(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            ArrayList list = new ArrayList();
            Array enumValues = Enum.GetValues(type);

            foreach (Enum value in enumValues)
            {
                list.Add(new KeyValuePair<Enum, string>(value, GetDescription(value)));
            }

            return list;
        }

        /// <summary>
        /// Convert enum to DataTable
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static DataTable ToDataTable(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            DataTable result = new DataTable();
            result.Columns.Add("MA", typeof(int));
            result.Columns.Add("TEN");

            ArrayList list = new ArrayList();
            Array enumValues = Enum.GetValues(type);

            foreach (Enum value in enumValues)
            {
                result.Rows.Add(value, GetDescription(value));
            }

            return result;
        }
    }
}

